#include <stdio.h>
#include <unistd.h>
#include "MQTTClient.h"
#include "onenet.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_adc.h"
#include "hi_errno.h"


#define ONENET_INFO_DEVID "982335152" /*设备ID*/
#define ONENET_INFO_AUTH "gerhardt1024" /*鉴权信息*/
#define ONENET_INFO_APIKEY "t116ZOgsQWy6qbzd7AmY7IEYOkQ="/*设备APIKEY*/
#define ONENET_INFO_PROID "538092" /*产品ID*/
#define ONENET_MASTER_APIKEY "DC4gz1UmcpP8=iR0Jb5HEbbCHgA="/*产品Master-APIkey*/


extern int rand(void);


void onenet_cmd_rsp_cb(uint8_t *recv_data, size_t recv_size, uint8_t **resp_data, size_t *resp_size)
{
    printf("recv data is %.*s\n", recv_size, recv_data);

    *resp_data = NULL;
    *resp_size = 0;
}

int onenet_test(void)
{
	
    device_info_init(ONENET_INFO_DEVID, ONENET_INFO_PROID, ONENET_INFO_AUTH, ONENET_INFO_APIKEY, ONENET_MASTER_APIKEY);
    onenet_mqtt_init();

    onenet_set_cmd_rsp_cb(onenet_cmd_rsp_cb);

	while (1)
    {
		int value = 0;
		
        value = AdcGpioTask();
        if (onenet_mqtt_upload_digit("tds", value) < 0)
        {
            printf("upload has an error, stop uploading");
        }
        else
        {
            /* TDS解算 */
            printf("buffer : {\"tds\":%d} \r\n", (int)(3463 - (865.68 * (value / 819))));
        }
        sleep(1);
    }
	return 0;
}
/**
 * @brief ADC 获取电压值
 * 
 * @return int 
 */
int AdcGpioTask(){

    int value;
        if(hi_adc_read(HI_ADC_CHANNEL_4, &value, HI_ADC_EQU_MODEL_4, HI_ADC_CUR_BAIS_DEFAULT, 0) != HI_ERR_SUCCESS){
            printf("ADC read error!\n");
        }else{
            printf("ADC_VALUE = %d\n", (int)value);
            usleep(2000);
        }
    
    return value;
}